package cn.rocksolid.sport.common.http.utils;

import cn.rocksolid.sport.common.C;
import cn.rocksolid.sport.common.Constant.AccessType;
import cn.rocksolid.sport.common.error.RSE;
import cn.rocksolid.sport.common.error.RockSolidException;
import cn.rocksolid.sport.common.utils.AssertUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpUtils {
  private static final int DEFAULT_PAGE = 1;
  private static final int DEFAULT_PER_PAGE = 10;
  private static final String IP_UNKNOWN = "unknown";
  private static final String MULTI_IP_SEPARATOR = ",";
  private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

  private HttpUtils() {
  }

  public static <T> Page<T> resolve() {
    if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes) {
      ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      HttpServletRequest req = sra.getRequest();
      AssertUtils.isNotNull(req, RSE.INVALID_HTTP_REQ);
      Page<T> pagination = new Page<>();
      pagination.setCurrent(castIntOrDefault(req.getParameter(C.PAGE.f), DEFAULT_PAGE));
      pagination.setSize(castIntOrDefault(req.getParameter(C.PER_PAGE.f), DEFAULT_PER_PAGE));
      return pagination;
    }
    throw new RockSolidException(RSE.INVALID_HTTP_REQ);
  }

  private static int castIntOrDefault(String s, int defaultVal) {
    try {
      return Integer.parseInt(s);
    } catch (NumberFormatException nfe) {
      return defaultVal;
    }
  }

  public static AccessType retrieveAccessType(final HttpServletRequest httpRequest) {
    String accessType = retrieveProp(httpRequest, C.ACCESS_TYPE.p);
    if (StringUtils.isBlank(accessType)) {
      return null;
    }
    return AccessType.valueOf(accessType);
  }

  public static String retrieveProp(final HttpServletRequest httpRequest, final String prop) {
    String propValue = httpRequest.getHeader(prop);
    if (StringUtils.isBlank(propValue)) {
      return httpRequest.getParameter(prop);
    }
    return propValue;
  }

  /**
   * 获取IP地址
   * <p>
   * 使用NGINXF等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
   * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
   */
  public static String retrieveIpAddress(HttpServletRequest request) {
    String ip = null;
    try {
      ip = request.getHeader("x-forwarded-for");
      if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
      }
      if (StringUtils.isBlank(ip) || ip.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
      }
      if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
      }
      if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
      }
      if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
      }
    } catch (Exception exp) {
      LOGGER.error("HttpUtils retrieve IP address error.", exp);
    }
    // If under the proxy it will use first IP address.
    if (StringUtils.isNotBlank(ip) && StringUtils.contains(ip, MULTI_IP_SEPARATOR)) {
      return ip.substring(0, ip.indexOf(MULTI_IP_SEPARATOR));
    }
    return ip;
  }
}
